package cn.meeh.sscircle.module.account;

import android.graphics.Color;
import android.os.Handler;
import android.os.Message;
import android.os.Bundle;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import org.androidannotations.annotations.Background;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.UiThread;
import org.androidannotations.annotations.ViewById;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import cn.meeh.sscircle.R;
import cn.meeh.sscircle.common.util.NetworkUtils;
import cn.meeh.sscircle.config.Evn;
import cn.meeh.sscircle.module.base.ActionBarBaseActivity;
import cn.smssdk.EventHandler;
import cn.smssdk.SMSSDK;

@EActivity(R.layout.activity_verify_phone)
public class VerifyPhoneActivity extends ActionBarBaseActivity {

    @ViewById
    LinearLayout verify_phone_ll;
    @ViewById(R.id.verify_phonenum_et)
    EditText phoneNumET;
    @ViewById
    Button phone_next_btn;

    @ViewById
    LinearLayout verify_code_ll;
    @ViewById(R.id.verify_code_et)
    EditText codeET;
    @ViewById
    TextView get_verify_btn;
    @ViewById
    Button post_verify_btn;

    @ViewById
    LinearLayout verify_password_ll;
    @ViewById
    EditText passwd_et;
    @ViewById
    ImageView show_passwd_tv;
    @ViewById
    Button verify_reg_bt;


    private String PHONENUM;
    private int time = 60;
    private boolean AgainValid=false; //获取验证码锁
    private int STEP= Evn.VERIFY_STEP_1_PHONENUM;
    private int TYPE = Evn.VERIFY_TYPE_REG;
    private boolean isPasswdShow =false;



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initView();
        initData();
        SMSSDK.initSDK(this, Evn.SMSSDK_APPKEY, Evn.SMSSDK_APPSECRET);
        EventHandler eh=new EventHandler(){
            @Override
            public void afterEvent(int event, int result, Object data) {
                Message msg = new Message();
                msg.arg1 = event;
                msg.arg2 = result;
                msg.obj = data;
                handler.sendMessage(msg);
            }
        };
        SMSSDK.registerEventHandler(eh);
    }

    //初始化View
    void initView()
    {
        actionBar.getActionLeftIV().setVisibility(View.VISIBLE);
        actionBar.getActionLeftIV().setText("返回");
        actionBar.getActionLeftIV().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                back();
            }
        });
    }
    //初始化数据
    void initData()
    {
        TYPE = getIntent().getIntExtra("verify_type",Evn.VERIFY_TYPE_REG);
        switch (TYPE)
        {
            case Evn.VERIFY_TYPE_REG:
                verify_reg_bt.setText("立即注册");
                break;
            case Evn.VERIFY_TYPE_FORGET:
                verify_reg_bt.setText("重置密码");
                break;
        }
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if(keyCode==KeyEvent.KEYCODE_BACK) {
            back();
            return true;
        }
        return super.onKeyUp(keyCode, event);
    }


    //获取验证码
    @Click(R.id.get_verify_btn)
    void getVerifyNum()
    {
        if(AgainValid) {
            GetVerifyCode();
        }
    }
    //校验验证码
    @Click(R.id.post_verify_btn)
    void postVerifyNum()
    {
        if(!"".equals(codeET.getText().toString())){
            SMSSDK.submitVerificationCode("86", PHONENUM, codeET.getText().toString());
        }else {
            Toast.makeText(getApplicationContext(), "验证码不能为空", Toast.LENGTH_SHORT).show();
        }
    }
    //
    @Click(R.id.phone_next_btn)
    void phoneNextSteup()
    {
        if(NetworkUtils.isNetworkAvailable(this)) {
            if (isMobileNO(phoneNumET.getText().toString())) {
                PHONENUM = phoneNumET.getText().toString();
                GetVerifyCode();
            }else
                Toast.makeText(getApplicationContext(),"请输入正确的手机号码",Toast.LENGTH_SHORT).show();
        }else
            Toast.makeText(getApplicationContext(), "你的网络不给力，请稍后再试", Toast.LENGTH_SHORT).show();
    }

    @Click(R.id.show_passwd_tv)
    void showPasswd() {
        if (isPasswdShow) {
            // hide password
            passwd_et.setTransformationMethod(PasswordTransformationMethod.getInstance());
            show_passwd_tv.setImageResource(R.mipmap.password_hide);
        } else {
            // display password text
            passwd_et.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
            show_passwd_tv.setImageResource(R.mipmap.password_show);
        }
        isPasswdShow = !isPasswdShow;
        passwd_et.postInvalidate();
        passwd_et.setSelection(passwd_et.getText().length());
    }

    //SMSSDK事件回调
    Handler handler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            // TODO Auto-generated method stub
            super.handleMessage(msg);
            int event = msg.arg1;
            int result = msg.arg2;
            Object data = msg.obj;
            if (result == SMSSDK.RESULT_COMPLETE) {
                if (event == SMSSDK.EVENT_SUBMIT_VERIFICATION_CODE) {
                    Toast.makeText(getApplicationContext(),"提交验证码成功",Toast.LENGTH_SHORT).show();
                } else if (event == SMSSDK.EVENT_GET_VERIFICATION_CODE){
                    if(STEP==Evn.VERIFY_STEP_1_PHONENUM)//请求成功，转换页面
                    {
                        setPageState(Evn.VERIFY_STEP_2_VERIFYCODE);
                    }
                    Toast.makeText(getApplicationContext(),"验证码已经发送，请稍等",Toast.LENGTH_SHORT).show();
                }
            } else {
                if (event == SMSSDK.EVENT_SUBMIT_VERIFICATION_CODE) {
                    Toast.makeText(getApplicationContext(),"验证码错误，请检查后再提交",Toast.LENGTH_SHORT).show();
                    ((Throwable) data).printStackTrace();
                } else if (event == SMSSDK.EVENT_GET_VERIFICATION_CODE){
                    Toast.makeText(getApplicationContext(),"验证码请求失败，请检查网络",Toast.LENGTH_SHORT).show();
                    ((Throwable) data).printStackTrace();
                }else {
                    Toast.makeText(getApplicationContext(), "出现错误，请稍后再试", Toast.LENGTH_SHORT).show();
                    ((Throwable) data).printStackTrace();
                }
            }
        }
    };

    @Background
    void doSomeStuffInBackground() {
        try {
            while (time>0)
            {
                time--;
                publishProgress();
                Thread.sleep(1000);
            }
        } catch (Exception e) {
            // TODO: handle exception
        }
    }

    @UiThread
    void publishProgress() {
        if(time>0)
        {
            AgainValid=false;
            get_verify_btn.setTextColor(Color.parseColor("#c6c6c6"));
            get_verify_btn.setText("重新发送("+time+")");
        }else
        {
            AgainValid=true;
            get_verify_btn.setTextColor(Color.parseColor("#27283c"));
            get_verify_btn.setText("重新发送");
        }
    }

    //判断手机号码
    public boolean isMobileNO(String mobiles) {
        Pattern p = Pattern.compile("^((13[0-9])|(15[^4,\\D])|(18[0-9]))\\d{8}$");
        Matcher m = p.matcher(mobiles);
        return m.matches();
    }

    //获取验证码
    public void GetVerifyCode()
    {
        if(isMobileNO(PHONENUM)){
            SMSSDK.getVerificationCode("86",PHONENUM);
            time=60;
            doSomeStuffInBackground();
        }else {
            Toast.makeText(VerifyPhoneActivity.this, "电话不能为空", Toast.LENGTH_SHORT).show();
        }
    }

    //设置页面状态
    private void setPageState(int step)
    {
        STEP = step;
        switch (STEP)
        {
            case Evn.VERIFY_STEP_1_PHONENUM:
                verify_phone_ll.setVisibility(View.VISIBLE);
                verify_code_ll.setVisibility(View.GONE);
                verify_password_ll.setVisibility(View.GONE);
                actionBar.getTitleTV().setText("填写手机号码");
                break;
            case Evn.VERIFY_STEP_2_VERIFYCODE:
                verify_phone_ll.setVisibility(View.GONE);
                verify_code_ll.setVisibility(View.VISIBLE);
                verify_password_ll.setVisibility(View.GONE);
                codeET.setText("");//清空验证码输入框
                actionBar.getTitleTV().setText("输入验证码");
                break;
            case Evn.VERIFY_STEP_3_PASSWORD:
                verify_phone_ll.setVisibility(View.GONE);
                verify_code_ll.setVisibility(View.GONE);
                verify_password_ll.setVisibility(View.VISIBLE);
                passwd_et.setText("");//清空密码框
                actionBar.getTitleTV().setText("输入密码");
                break;
        }
    }

    //后退操作
    private void back()
    {
        switch (STEP)
        {
            case Evn.VERIFY_STEP_1_PHONENUM:
                this.finish();
                break;
            case Evn.VERIFY_STEP_2_VERIFYCODE:
                setPageState(Evn.VERIFY_STEP_1_PHONENUM);
                break;
            case Evn.VERIFY_STEP_3_PASSWORD:
                setPageState(Evn.VERIFY_STEP_1_PHONENUM);
                break;
        }
    }
}
